package streaming.api.source;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import utils.PropertiesReader;

/**
 *  基于Socket协议获取数据
 *  env.socketTextStream
 */
public class Source3_socketTextStream {

    private static String socketIP = PropertiesReader.get("default.socket.ip");
    private static Integer socketPort = PropertiesReader.getInteger("default.socket.port");

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //从Socket文本流读取数据
        DataStreamSource<String> inputDataStream = env.socketTextStream(socketIP, socketPort);
        //转换数据流（二元组）
//        DataStream<Tuple2<String, Integer>> resultStream = inputDataStream.flatMap(new ST3FlatMapper());
//        resultStream.print("resultStream:");
//        //计算
//        SingleOutputStreamOperator<Tuple2<String, Integer>> countStream = resultStream.keyBy(0).sum(1);
//        countStream.print("countStream:");
        inputDataStream.print("data:");
        //执行任务
        env.execute();
    }

    /**
     * String字符串转二元数组
     */
    public static class ST3FlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        private String separator = ",";

        public ST3FlatMapper() {
            super();
        }

        public ST3FlatMapper(String separator) {
            this.separator = separator;
        }

        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> out) throws Exception {
            // 按空格分词
            String[] words = s.split(separator);
            // 遍历所有word，包成二元组输出
            for (String word: words) {
                out.collect(new Tuple2<String, Integer>(word, 1));
            }
        }
    }

}
